package jp.co.sharp.android.parents.kidsguard.activity.mimamori;

import android.app.NotificationManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.common.MimamoriBusinessService;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.profile.ProfileClipActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.ContactOptActivity;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestCodeConstants;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;

public class MimamoriAlertActivity extends AppCompatActivity {

    private final static int REQUEST_READ_PHONE_STATE_PERMISSION = 0;

    private final static int CONTACT_CODE = 100;

    private final static int PERMISSIONS_CODE = 1000;

    private final static int ALARM_CODE = 1;

    private ImageView mBackIv;

    private TextView mRingNameTv;

    private TextView mParentTelTv;

    private Switch mRingSw;

    private Switch mShockSw;

    private KidInfoEntity mKidInfoEntity;

    private MimamoriBusinessService mMimamoriBusinessService;

    private boolean mUnReceiver = false;

    private App mApp;

    private static final String TAG = "TAG";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "MimamoriAlertActivity_onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mimamori_alert);
        mounted();
        init();
        mApp = (App)getApplication();
        mMimamoriBusinessService = new MimamoriBusinessService(MimamoriAlertActivity.this,
                (App)getApplication(), new Intent(getIntent()), (NotificationManager)getSystemService(NOTIFICATION_SERVICE));
    }

    @Override
    public void onBackPressed() {
        backToHome();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "ProfileEditActivity_onStart");
        mMimamoriBusinessService.registerReceiver();
        mUnReceiver = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ProfileEditActivity_onStop");
        if (!mUnReceiver) {
            try {
                mMimamoriBusinessService.unRegisterReceiver();
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    // Ignore this exception. This is exactly what is desired
                    Log.e(TAG, e.getMessage());
                } else {
                    // unexpected, re-throw
                    Log.e(TAG, e.getMessage());
                }
            }
            mUnReceiver = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ProfileEditActivity_onDestroy");
        if (!mUnReceiver) {
            try {
                mMimamoriBusinessService.unRegisterReceiver();
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    // Ignore this exception. This is exactly what is desired
                    Log.e(TAG, e.getMessage());
                } else {
                    // unexpected, re-throw
                    Log.e(TAG, e.getMessage());
                }
            }
            mUnReceiver = true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Log.i(TAG, "MimamoriAlertActivity_onActivityResult_requestCode:"+requestCode);
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == CONTACT_CODE) {
            if (intent != null && intent.hasExtra(Constants.KEY_CONTACT_OPT)){
                ContactListDto contactListDto =(ContactListDto)intent.getSerializableExtra(Constants.KEY_CONTACT_OPT);
                mParentTelTv.setText(contactListDto.getPhone());
                mKidInfoEntity.setParentTel(contactListDto.getPhone());
                ((App) getApplication()).updateKidInfo(mKidInfoEntity);
            }
        }
        if (requestCode == ALARM_CODE) {
            if (intent != null) {
                Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
                RingtoneManager manager = new RingtoneManager(this);
                manager.setType(RingtoneManager.TYPE_RINGTONE);
                Ringtone ringtone = RingtoneManager.getRingtone(this, uri);
                String title = ringtone.getTitle(this);
                mKidInfoEntity.setRingToneName(title);
                mKidInfoEntity.setRingToneUrl(uri.toString());
                mRingNameTv.setText(title);
                ((App) getApplication()).updateKidInfo(mKidInfoEntity);
            }
        }
        if (requestCode == PERMISSIONS_CODE) {
            if (intent != null) {
                checkPermissions();
            }
        } else if (requestCode == RequestCodeConstants.MIMAMORI_CONTACT_ADD) {
            // Mimamori Add Contact
            mMimamoriBusinessService.onContactAddResult(true);
        }
    }

    private void mounted() {
        Log.i(TAG, "MimamoriAlertActivity_mounted");
        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        mBackIv = (ImageView) findViewById(R.id.imageViewBack);
        mRingNameTv = (TextView) findViewById(R.id.textViewRingName);
        mParentTelTv = (TextView) findViewById(R.id.textViewParentTel);
        mRingSw = findViewById(R.id.switchRing);
        mShockSw = findViewById(R.id.switchShock);
        mBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                backToHome();
            }
        });
        mParentTelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toPhoneChoose();
            }
        });
        mRingSw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    mRingSw.setChecked(mRingSw.isChecked());
                    mKidInfoEntity.setRingToneSwitch(mRingSw.isChecked());
                    ((App) getApplication()).updateKidInfo(mKidInfoEntity);
            }
        });
        mShockSw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    mShockSw.setChecked(mShockSw.isChecked());
                    mKidInfoEntity.setShockSwitch(mShockSw.isChecked());
                    ((App) getApplication()).updateKidInfo(mKidInfoEntity);
            }
        });
        mRingNameTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                    switchShock.setChecked(!switchShock.isChecked());
//                    kidInfoEntity.setShockSwitch(switchShock.isChecked());
//                    ((App)getApplication()).updateKidInfo(kidInfoEntity);
                    Uri url = Uri.parse(mKidInfoEntity.getRingToneUrl());
                    Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "着信音一覧");
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
                    if (url == null || url.equals("")) {
                        url = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                    }
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, url);
                    startActivityForResult(intent, ALARM_CODE);
            }
        });

    }

    private void init() {
        Log.i(TAG, "MimamoriAlertActivity_init");
        if (mKidInfoEntity.getRingToneName() != null && mKidInfoEntity.getRingToneName().length() > 0) {
            mRingNameTv.setText(mKidInfoEntity.getRingToneName());
        } else {
            //这里写获取本机的铃声第一个
            Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE);
            Ringtone ringtone = RingtoneManager.getRingtone(this, url);
            String name = ringtone.getTitle(this);
            mKidInfoEntity.setRingToneUrl(url.toString());
            mRingNameTv.setText(name);
            ((App) getApplication()).updateKidInfo(mKidInfoEntity);
        }
        if (mKidInfoEntity.getParentTel() != null && mKidInfoEntity.getParentTel().length() > 0) {
            mParentTelTv.setText(mKidInfoEntity.getParentTel());
        } else {
            checkPermissions();
        }
        mRingSw.setChecked(mKidInfoEntity.getRingToneSwitch() != null ? mKidInfoEntity.getRingToneSwitch() : false);
        mShockSw.setChecked(mKidInfoEntity.getShockSwitch() != null ? mKidInfoEntity.getShockSwitch() : false);
    }

    private void backToHome() {
        Log.i(TAG, "MimamoriAlertActivity_backToHome");
        Intent intent = new Intent();
        intent.setClass(this, HomeActivity.class);
        startActivity(intent);
    }

    private void toPhoneChoose() {
        Log.i(TAG, "MimamoriAlertActivity_toPhoneChoose");
        Intent intent = new Intent();
        intent.setClass(MimamoriAlertActivity.this, ContactOptActivity.class);
        startActivityForResult(intent,CONTACT_CODE);
    }

    private void checkPermissions() {
        Log.i(TAG, "MimamoriAlertActivity_checkPermissions");
        ActivityCompat.requestPermissions(MimamoriAlertActivity.this, new String[]{android.Manifest.permission.READ_PHONE_STATE,android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_PHONE_STATE_PERMISSION);


    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.i(TAG, "MimamoriAlertActivity_onRequestPermissionsResult");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Boolean phonePermissionFlag = false;
        Boolean storagePermissionFlag = false;
        if (requestCode == REQUEST_READ_PHONE_STATE_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                phonePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[0])){
                    Toast.makeText(this, "Read Phone State Permissionの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    startActivityForResult(intent,PERMISSIONS_CODE);
                    return;
                }
            }
            if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                storagePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[1])){
                    Toast.makeText(this, "Read External Storage Permissionの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    startActivityForResult(intent,PERMISSIONS_CODE);
                }
            }
        }
        if(storagePermissionFlag && phonePermissionFlag) {
            setPhoneNumber();
        }

    }

    private void setPhoneNumber(){
        Log.i(TAG, "MimamoriAlertActivity_setPhoneNumber");
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(this.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this,android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED ) {
            return;
        }
        String parentTel = telephonyManager.getLine1Number();
        if (parentTel != null){
            mParentTelTv.setText(parentTel);
            mKidInfoEntity.setParentTel(parentTel);
            ((App)getApplication()).updateKidInfo(mKidInfoEntity);
        }else {
            mParentTelTv.setText("");
            mKidInfoEntity.setParentTel("");
            ((App)getApplication()).updateKidInfo(mKidInfoEntity);
        }
    }

}
